<template>
    <div style="div">
        <el-upload
            action="#"
            ref ="upload"
            list-type="picture-card"
            :limit="fileNum"
            :on-exceed = "exceeds"
            :on-change= "changeUpload"
            :on-remove="handleRemove"
            :file-list="fileList"
            :class="{hide:hideUpload}"
            :auto-upload="false">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                <video
                    class="el-upload-list__item-thumbnail"
                    :src="file.url" alt=""
                >
                </video>
                </div>
        </el-upload>
    </div>
</template>
<script>
import { policy } from '@/api/policy'
import $ from 'jquery'
export default {
    data(){
        return {
            changes:true,
            hideUpload: false,
            imgUrl:"",
            imgFlag:[],
            aliyunOssToken:[]
        }
    },
    props:{
      fileList: Array,
      fileNum:Number,
    //   hideUpload:Boolean,
      required: true
    },
    created(){
        // this.getPolicy()
    },
    methods:{
        //获取签名
        getPolicy(){
            policy().then(res=>{
                // console.log(res)
                this.aliyunOssToken = res.data.data
                this.imgUrl = res.data.data.host
                var imgUrlPrefix = this.aliyunOssToken.host 
                var dir = this.aliyunOssToken.dir 
                sessionStorage.setItem("imgUrlPrefix",imgUrlPrefix)
                sessionStorage.setItem("dir",dir)
            })
        },
        //图片上传限制提示
        exceeds(){
            this.$message.error('不能上传了');
        },
        // 图片上传改变时
        changeUpload(file, fileList){
            if(fileList.length >= this.fileNum){
                this.changes = true
            }else{
                this.changes = false
            }
            this.hideUpload = fileList.length >= this.fileNum;
            // console.log(file, fileList);
        },
        // 图片移除时
        handleRemove(file, fileList) {
            if(fileList.length >= this.fileNum){
                this.changes = true
            }else{
                this.changes = false
            }
            this.hideUpload = fileList.length >= this.fileNum;
            console.log(fileList);
        },
        changeStatus(){
            return this.changes
        },
        //字符串截取
        getCaption(obj){
            var index=obj.lastIndexOf(".com");
            obj=obj.substring(index+4,obj.length);
            return obj;
        },
        //图片上传
        submitUpload() {
            this.imgFlag=[]
            let _self = this
            let oldList=[];
            let newList=[];
            // console.log(oldList)
            // console.log(newList)
            for(var i=0;i<this.$refs.upload.uploadFiles.length;i++){
                if(this.$refs.upload.uploadFiles[i].name){
                    newList.push(this.$refs.upload.uploadFiles[i])
                }else{
                    oldList.push(this.$refs.upload.uploadFiles[i])
                }
            }
            for(var k=0;k<oldList.length;k++){
                this.imgFlag.push(this.getCaption(oldList[k].url))
            }
            if(newList.length>0){
                for(let k=0;k<newList.length;++k){ 
                    var file = newList[k].name
                    var getSuffix = function (fileName) {
                        var pos = fileName.lastIndexOf(".");
                        var suffix = '';
                        if (pos != -1) {
                            suffix = fileName.substring(pos);
                        }
                        return suffix;
                    }
                    //利用时间戳生成uuid
                    var d = new Date().getTime();
                    if (window.performance && typeof window.performance.now === "function") {
                        d += performance.now(); //use high-precision timer if available
                    }
                    var uuid = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                        var r = (d + Math.random() * 16) % 16 | 0;
                        d = Math.floor(d / 16);
                        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
                    });
                    //定义文件名
                    var filename = uuid + getSuffix(file);
                    //注意formData里append添加的键的大小写
                    var formData = new FormData();
                    //存储在oss的文件路径
                    formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); 
                    //accessKeyId
                    formData.append('key', _self.aliyunOssToken.dir+ "/"+ filename); 
                    //policy
                    formData.append('policy', _self.aliyunOssToken.policy); 
                    //签名
                    //如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
                    formData.append('Signature', _self.aliyunOssToken.signature); 
                    // 文件详情
                    formData.append("file", newList[k].raw);
                    //成功后返回的操作码
                    formData.append('success_action_status', 200); 
                    var url = _self.aliyunOssToken.host;
                    var fileUrl = _self.aliyunOssToken.host +'/'+ _self.aliyunOssToken.dir +"/"+ filename;
                    this.imgFlag.push('/'+ _self.aliyunOssToken.dir +"/"+ filename)
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: formData,
                        async: false,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: function (data) {
                            // console.log(data);
                        },
                        error: function (data) {
                            // console.log(data);
                            return "uploadError"
                        }
                    });
                }
            }
            return this.imgFlag
        }
    }
}
</script>
<style scoped>
.div,.div>div{display: inline;}
</style>
